import 'package:flutter/material.dart';
import 'package:flutterapp/common/base/base_mode.dart';
import 'package:flutterapp/common/base/base_page.dart';
import 'package:flutterapp/common/base/base_provider.dart';
import 'package:flutterapp/common/constant/API.dart';
import 'package:flutterapp/common/util/router_helpe_utils.dart';
import 'package:flutterapp/common/util/log_utils.dart';
import 'package:flutterapp/common/util/theme_data_utils.dart';
import 'package:flutterapp/http/http_utils.dart';
import 'package:flutterapp/system/SystemItemDetailsPage.dart';
import 'package:flutterapp/system/entity/system_tree_entity.dart';

class SystemPage extends StatefulWidget {
  ///标题
  final String? title;

  const SystemPage({Key? key, this.title}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return SystemPageState();
  }
}

class SystemPageState extends State<SystemPage>
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);

    return BaseProvider<SystemModel>(
      model: SystemModel(),
      modelBuilder: (context, model) {
        return BasePage(
          title: widget.title ?? '',
          child: Container(
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          Container(
            width: 100.0,
            child: ListView.separated(
              itemCount: model.systemTreeEntity?.data?.length ?? 0,
              separatorBuilder: (buildContext, index) {
                return Divider(
                  height: 2.0,
                  color: Colors.grey[400],
                );
              },
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  color: index == model.selectedPosition
                      ? Colors.grey[100]
                      : Colors.white,
                  child: Row(
                    children: <Widget>[
                      Visibility(
                        visible: index == model.selectedPosition,
                        child: Container(
                          color: Theme.of(context).primaryColor ==
                                  ThemeDataUtils.white
                              ? Colors.blueAccent
                              : Theme.of(context).primaryColor,
                          width: 5.0,
                          height: 30.0,
                        ),
                      ),
                      Expanded(
                        child: ListTile(
                          title: Text(
                              model.systemTreeEntity!.data![index].name ?? '',
                              style: TextStyle(
                                  color: index == model.selectedPosition
                                      ? (Theme.of(context).primaryColor ==
                                              ThemeDataUtils.white
                                          ? Colors.blueAccent
                                          : Theme.of(context).primaryColor)
                                      : Colors.black,
                                  fontSize: 13.0)),
                          onTap: () {
                            setState(() {
                              //设置被点击位置
                              model.selectedPosition = index;
                              //设置应该被展示的二级标题
                              model.secondTitleData =
                                  model.systemTreeEntity!.data![index];
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                );
              },
              physics: BouncingScrollPhysics(),
            ),
          ),
          Expanded(
            child: Container(
              color: Colors.grey[100],
              height: double.infinity,
              width: double.infinity,
              padding: EdgeInsets.all(10.0),
              child: SingleChildScrollView(
                child: Wrap(
                  spacing: 10.0, // 主轴(水平)方向间距
                  runSpacing: 4.0, // 纵轴（垂直）方向间距
                  alignment: WrapAlignment.start, //沿主轴方向居中
                  children: getSecondTitleTreeItemWidgets(model.secondTitleData),
                ),
              ),
            ),
          ), //一级标题
          //二级标题
        ],
      ),
    ),
        );
      },
    );
  }

  @override
  void initState() {
    super.initState();
  }

  ///获取二级标题item组件集合
  List<Widget> getSecondTitleTreeItemWidgets(SystemTreeData? systemTreeData) {
    var titleTreeWidgets = <Widget>[];
    if (systemTreeData?.children != null &&
        systemTreeData!.children!.length > 0) {
      for (var i = 0; i < systemTreeData.children!.length; i++) {
        var child = systemTreeData.children![i];
        titleTreeWidgets.add(ElevatedButton(
            child: Text(
              child.name ?? '',
            ),
            // color: Theme.of(context).primaryColor == MyColors.white ? Colors.blueAccent : Theme.of(context).primaryColor,
            // highlightColor: Theme.of(context).primaryColor,
            // colorBrightness: Brightness.dark,
            // splashColor: Colors.grey[700],
            // shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
            onPressed: () {
              RouteHelpUtils.push(
                  context,
                  SystemItemDetailsPage(
                    title: systemTreeData.name,
                    tabList: systemTreeData.children,
                    position: i,
                  ));
            }));
      }

      LogUtils.d("第一个标题为:${systemTreeData.children![0].name}");
    }

    LogUtils.d("titleTreeWidgets的长度为:${titleTreeWidgets.length}");

    return titleTreeWidgets;
  }


  @override
  bool get wantKeepAlive => true;
}

class SystemModel extends BaseModel {
  /// 标题数据
  SystemTreeEntity? systemTreeEntity;

  /// 被选中的一级标题,默认选中第一个
  int selectedPosition = 0;

  ///应该展示的二级目录标题数据
  SystemTreeData? secondTitleData;

  @override
  Future<bool> init() {
    return initTreeData();
  }

  ///初始化标题数据
  Future<bool> initTreeData() {
    return HttpUtils.getInstance().get<SystemTreeEntity>(API.systemTree,
        onSuccess: (data) {
      //设置标题数据
      systemTreeEntity = data;
      //设置二级标题数据
      if (systemTreeEntity?.data != null &&
          systemTreeEntity!.data!.length > 0) {
        secondTitleData = systemTreeEntity!.data![selectedPosition];
      }
      notifyListeners();
    }, isNeedCache: true).then((value) => value != null);
  }
}
